package com.wtpaint.lib.glide.load.model.data;

import android.net.Uri;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUriFetcher implements DataFetcher<InputStream> {

    private final Uri uri;

    private boolean isCanceled;

    public HttpUriFetcher(Uri uri) {
        this.uri = uri;
    }

    @Override
    public void loadData(DataFetcherCallback<InputStream> callback) {
        HttpURLConnection connection;
        InputStream is = null;
        try {
            URL url = new URL(uri.toString());
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            is = connection.getInputStream();
            int respCode = connection.getResponseCode();

            if (isCanceled) {
                return;
            }

            if (respCode == HttpURLConnection.HTTP_OK) {
                callback.onFetcherReady(is);
            } else {
                callback.onLoadFailed(new RuntimeException(connection.getResponseMessage()));
            }

        } catch (Exception e) {
            callback.onLoadFailed(e);
        } finally {
            try {
                if (null != is)
                    is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void cancel() {
        isCanceled = true;
    }
}
